<template lang="pug">
.content
  .container-fluid
    md-card(v-for="(msg, index) in messages",
    :key='index',
    :title='msg.user.name',
    :category='description(msg)',
    backgroundColor='orange')
      p 手机号： {{msg.user.phone}}， 公司： {{msg.user.company}}，邮件：{{msg.user.email}}
      p {{msg.user.misc}}
</template>

<script>
import axios from 'axios'
import MdNavTabs from '@/core/components/mdTab/nav-tabs'
import MdTabContent from '@/core/components/mdTab/tab-content'

let users = {}

export default {
  name: 'dashboard',
  components: {
    MdTabContent,
    MdNavTabs
  },
  created() {
    this.initMaclist()
    this.initSocket()
  },
  data() {
    return {
      maclist: '',
      messages: [{
        user: {
          name: 'IoT 监控',
          phone: '13800138000',
          company: 'IoT Center',
          email: 'bot@iot.com',
          disc: '这是 IoT 平台机器人的在线状态'
        },
        message: '来店',
        date: new Date()
      }]
    }
  },
  methods: {
    initSocket() {
      // eslint-disable-next-line
      var socket = io(process.env.WS_URL)
      console.log(process.env)
      socket.on('disconnection', function () {
        console.log('[WS] disconnected')
      })
      socket.on('connection', function () {
        console.log('[WS] connected')
      })
      socket.on('ctrl', function (msg) {
        console.log('[WS] ctrl:', msg)
      })
      socket.on('maclist', (list) => {
        console.log('[WS] maclist', list)
        list.forEach(mac => {
          if (this.maclist.indexOf(mac.bssid) > -1) {
            console.log(mac.bssid, 'matched, fetching user')
            this.addMessage(mac)
          } else {
            console.log(mac.bssid, 'not matching')
          }
        })
      })
    },
    getUserByMAC(bssid) {
      if (users[bssid]) {
        return Promise.resolve(users[bssid])
      }
      return axios.get(process.env.API_URL + '/users/mac/' + bssid)
      .then(res => {
        return (users[bssid] = res.data)
      })
    },
    addMessage(mac) {
      this.getUserByMAC(mac.bssid).then(user => {
        this.messages.unshift({
          message: '来店',
          user: user,
          date: new Date(mac.date)
        })
      })
    },
    description(msg) {
      return `于 ${msg.date.toLocaleString()} ${msg.message}`
    },
    initMaclist() {
      axios.get(process.env.API_URL + '/users/maclist')
      .then(res => {
        this.maclist = res.data
        console.log('maclist fetched:', res.data)
      })
    }
  }
}
</script>
